'''
    设置右键菜单
'''

import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
from tkinter import simpledialog as sd


class application(tk.Frame):
    def __init__(self,master=None):
        self.master=master
        super().__init__(self.master)
        self.path = 'O:\python\tkinter\zyg\tkinter'
        self.creatWidget()
        self.creatMousemenu()

    def creatWidget(self):
        self.menubar=tk.Menu(self.master)
        self.menuFile=tk.Menu(self.menubar)
        self.menuEdit=tk.Menu(self.menubar)
        self.menuHelp=tk.Menu(self.menubar)

        self.menubar.add_cascade(label='文件',menu=self.menuFile)
        self.menubar.add_cascade(label='编辑',menu=self.menuEdit)
        self.menubar.add_cascade(label='帮助',menu=self.menuHelp)

        self.menuFile.add_command(label='新建',accelerator="ctrl+n",command=self.creat_)
        self.menuFile.add_command(label='打开',accelerator='ctrl+o',command=self.open_)
        self.menuFile.add_command(label='保存',accelerator='ctrl+s',command=self.save_)
        self.menuFile.add_separator()
        self.menuFile.add_command(label='退出',accelerator='ctrl+q',command=self.quit_)

        self.menuEdit.add_command(label='复制',accelerator='ctrl+c',command=self.test)
        self.menuEdit.add_command(label='黏贴',accelerator='ctrl+v',command=self.test)
        self.menuEdit.add_command(labe='字体',accelerator='ctrl+f',command=self.test)

        self.master['menu']=self.menubar
        self.t1=tk.Text()
        self.t1.pack()

    def creatMousemenu(self):
            self.mouseMenu=tk.Menu(self.master)
            self.mouseMenu.add_command(label='字体')

            self.master.bind('<Button-1>',self.mouseTest)

    def mouseTest(self,event):
        self.mouseMenu.post(event.x_root,event.y_root)


    def test(self):
        messagebox.showinfo('测试','试试有没有反应')


    def quit_(self):
        result=messagebox.askokcancel('请选择','确认退出？')
        if result==True:
            self.master.destroy()

    def open_(self):
         self.t1.delete(1.0,tk.END)
         with filedialog.askopenfile(initialdir=self.path,filetypes=(('* txt'),),mode='rb') as f:
            txt=f.read().decode('utf-8')
         self.t1.insert(tk.END,txt)

    def creat_(self):
        self.fileName=sd.askstring(title='打开文件',prompt='请输入文件名')
        self.f=open(self.path+self.fileName,mode='w',encoding='utf-8')
        self.f.close()

    def save_(self):
        self.fileName=filedialog.askopenfilename(initialdir=self.path,filetypes=(("* txt"),))
        with open(self.fileName,mode='a',encoding='utf-8') as f:
            txt=self.t1.get(1.0,tk.END)
            f.write(txt)
        messagebox.showinfo('保存文件','文件已保存')


window=tk.Tk()
window.title('文本编辑器')
app=application(window)
window.mainloop()